package com.isias.system.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.isias.common.result.ResultCodeEnum;
import com.isias.model.system.SysMenu;
import com.isias.model.system.SysRoleMenu;
import com.isias.model.system.SysUser;
import com.isias.model.vo.AssginMenuVo;
import com.isias.model.vo.RouterVo;
import com.isias.system.Util.MenuUtil;
import com.isias.system.Util.RouterHelper;
import com.isias.system.handler.NodeException;
import com.isias.system.mapper.SysMenuMapper;
import com.isias.system.mapper.SysRoleMapper;
import com.isias.system.mapper.SysRoleMenuMapper;
import com.isias.system.service.SysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜单表 服务实现类
 * </p>
 *
 * @author fanyi
 * @since 2023-02-21
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {
    @Autowired
    SysMenuMapper sysMenuMapper;

    @Override
    public List<SysMenu> findNodes() {
        List<SysMenu> sysMenus = sysMenuMapper.selectList(null);
        //调用递归整合查出来的数据
        List<SysMenu> resultList = MenuUtil.FindNodes(sysMenus);

        return resultList;
    }

    @Override
    public boolean removeMenuById(String id) {
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysMenu::getParentId,id);
        Integer count = sysMenuMapper.selectCount(queryWrapper);
        if (count>0){
            throw new NodeException(ResultCodeEnum.NODE_ERROR);
        }
        int i = sysMenuMapper.deleteById(id);
        return i == 1;
    }

    @Autowired
    SysRoleMenuMapper sysRoleMenuMapper;
    @Override
    public List<SysMenu> findSysMenuByRoleId(String roleId) {
        //获取所有菜单 status=1
        List<SysMenu> list = sysMenuMapper.SelectMenusWithStatus();
        //根据角色id查询角色分配过的菜单列表
        List<SysRoleMenu> HaveMenu = sysRoleMenuMapper.selectList(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId,roleId));
        //分配菜单id与所有菜单相比，如果有相同的，让isSelect值为true
        List<String> roleMenuIds = new ArrayList<>();
        for (SysRoleMenu menu : HaveMenu) {
            roleMenuIds.add(menu.getMenuId());
        }
        //遍历所有权限列表
        for (SysMenu sysMenu : list) {
            if (roleMenuIds.contains(sysMenu.getId())){
                sysMenu.setSelect(true);
            }else {
                sysMenu.setSelect(false);
            }
        }
//        for (SysRoleMenu menu : HaveMenu) {
//            for (SysMenu sysMenu : list) {
//                if (menu.getId().equals(sysMenu.getId())){
//                    sysMenu.setSelect(true);
//                }
//            }
//        }
        //转换成树形结构为了最终显示
        List<SysMenu> resultList = MenuUtil.FindNodes(list);

        return resultList;

    }


    @Override
    public boolean doAssign(AssginMenuVo assginMenuVo) {
        SysRoleMenu sysRoleMenu = new SysRoleMenu();    //--1.1
        List<Integer> insert = new ArrayList<>();       //--1.2
        //删除之前的id
        sysRoleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>().eq(SysRoleMenu::getRoleId,assginMenuVo.getRoleId()));
        //重新save新的id
        //遍历所有传进来的id
        for (String id : assginMenuVo.getMenuIdList()) {
            //创建对象一个一个的save进去(对象创建在外边，节省内存)  --1.1
            sysRoleMenu.setMenuId(id);
            sysRoleMenu.setRoleId(assginMenuVo.getRoleId());

            int i = sysRoleMenuMapper.insert(sysRoleMenu);
            insert.add(i);      //--1.2
        }
        //校验成功与否
        if (insert.contains(0)){
            insert.clear();
            return false;
        }
        insert.clear();
        return true;
    }



    @Override
    public List<RouterVo> getUserMenuList(String id) {
        List<SysMenu> sysMenus;
        LambdaQueryWrapper<SysMenu> lqw = new LambdaQueryWrapper<>();
        //判断是否为超级管理员（id=1）
        if ("1".equals(id)){
            lqw.eq(SysMenu::getStatus,1);
            //排序
            lqw.orderByAsc(SysMenu::getSortValue);
            sysMenus = sysMenuMapper.selectList(lqw);
        }else {
            sysMenus=sysMenuMapper.FindMenuListUserId(id);
        }
        //排序为树形结构
        List<SysMenu> list = MenuUtil.FindNodes(sysMenus);
        //排序为路由的树形结构
        List<RouterVo> resultlist = RouterHelper.buildRouters(list);
        return resultlist;
    }

    @Override
    public List<String> getUserButtonList(String id) {
        List<SysMenu> sysMenus;
        LambdaQueryWrapper<SysMenu> lqw = new LambdaQueryWrapper<>();
        //判断是否为超级管理员
        if ("1".equals(id)){
            lqw.eq(SysMenu::getStatus,1);
             sysMenus = sysMenuMapper.selectList(lqw);
        }else {
            sysMenus=sysMenuMapper.FindMenuListUserId(id);
        }
        //找到按钮，返回最终集合(type=2)
        List<String> resultList = new ArrayList<>();
        for (SysMenu sysMenu : sysMenus) {
            if (sysMenu.getType()==2){
                resultList.add(sysMenu.getPerms());
            }
        }
        return resultList;
    }

    @Override
    public boolean updataStatus(String id, Integer status) {
        Integer integer = sysMenuMapper.updataStatus(id, status);
        if (integer == 1){
            return true;
        }else {
            return false;
        }
    }
}
